<?php

defined('SYSPATH') or die('No direct script access.');

/**
 * 处理新闻的controller
 *
 * @author liuxudong
 */
class Controller_Admin_News extends Controller_Admin_Based {

    /**
     * 添加新闻
     */
    public function action_add() {
        $name_template = '<a href="/admin/news/list/{id}" title="{name}新闻列表">{name}</a>';
        $conditional_name_template = '<a href="/admin/news/list/{id}" title="{name}新闻列表">[ {name} ]</a>';
        $content_data['catalog_tree'] = Catehelp::get_left_tree($name_template, $conditional_name_template, array('table' => 'cheers_main_newstypes', 'id' => 'chr_typeid', 'name' => 'chr_typename'));
        $content_data['product_ids'] = array();
        $content_data['is_conditional'] = FALSE;
        $catalog_opt_template = array(
            'name_box' => '<option value="{id}">{indentation}{name}</option>',
            'indentation' => '&nbsp;|&nbsp;&nbsp;'
        );
        $content_data['catalog_opt'] = Catehelp::tree_to_str(Catehelp::get_tree($catalog_opt_template, 0, 0, array('table' => 'cheers_main_newstypes', 'id' => 'chr_typeid', 'name' => 'chr_typename')));

        if ($_POST) {
            $current_time = time();
            $news = ORM::factory('cheers_main_new');

            $_POST['chr_createdate'] = $current_time;
            $_POST['chr_editdate'] = $current_time;
            $user = User::instance()->logged_in();
            $_POST['chr_creator'] = $user['chr_uid'];
            $_POST['chr_editor'] = $user['chr_uid'];
            $news->values($_POST);
            if ($news->check()) {
                $news->save();
                if ($news->saved()) {
                    $newstypefiles = ORM::factory('cheers_main_newsimage')
                            ->where('chr_flag', '=', 0)
                            ->find_all()
                            ->as_array();

                    if ($newstypefiles) {
                        DB::update('cheers_main_newsimages')
                                ->set(array('chr_imageid' => $news->chr_newsid, 'chr_filestype' => 2, 'chr_createdate' => $current_time, 'chr_flag' => 1))
                                ->where('chr_flag', '=', 0)
                                ->execute();
                    }
                    $data['chr_context'] = htmlspecialchars(Arr::get($_POST, 'chr_context', ''));
                    if ($data['chr_context']) {
                        $news_context = ORM::factory('cheers_main_newscontext');
                        $news_context->chr_newsid = $news->chr_newsid;
                        $news_context->chr_context = $_POST['chr_context'];
                        if ($news_context->check()) {
                            $news_context->save();
                        }
                    }
                    if (isset($context_id)) {
                        $news_context = ORM::factory('cheers_main_newscontext', $context_id);
                        $news_context->chr_newsid = $news->chr_newsid;
                        $news_context->save();
                    }
                    Message::set('新闻添加成功!');
                    Request::current()->redirect('/admin/news/add/');
                }
            }
        }
        $content = View::factory('admin/news/news_add', $content_data)->render();
        $this->template = View::factory('admin/template')->set('content', $content);
    }

    /**
     * 新闻列表
     */
    public function action_list() {
        $name_template = '<a href="/admin/news/list/{id}" title="{name}新闻列表">{name}</a>';
        $conditional_name_template = '<a href="/admin/news/list/{id}" title="{name}新闻列表">[ {name} ]</a>';
        $content_data['catalog_tree'] = Catehelp::get_left_tree($name_template, $conditional_name_template, array('table' => 'cheers_main_newstypes', 'id' => 'chr_typeid', 'name' => 'chr_typename'));

        /*         * **************新闻列表开始******************** */
        $users = ORM::factory('cheers_main_new');
        $count = $users->count_all();
        $pagination = Pagination::factory(
                        array(
                            'current_page' => array('source' => 'query_string', 'key' => 'page'),
                            'total_items' => $count,
                            'auto_hide' => 'FALSE',
                        )
        );
        $page_view = $pagination->render();
        $data = ORM::factory('cheers_main_new')
                ->order_by('chr_newsid', 'DESC')
                ->limit($pagination->items_per_page)
                ->offset($pagination->offset)
                ->find_all()
                ->as_array();


        $newscates_arr = array();
        $newscates = ORM::factory('cheers_main_newstype')
                        ->find_all()->as_array();
        foreach ($newscates as $key => $value) {
            $newscates_arr[$value->chr_typeid] = $value->chr_typename;
        }

        $content = View::factory('admin/news/news_list', $content_data)
                ->set('data', $data)
                ->set('page_view', $page_view)
                ->set('newscates_arr', $newscates_arr)
                ->render();
        $this->template = View::factory('admin/template')->set('content', $content);
    }

    /**
     * 新闻删除
     */
    public function action_delete() {
        $news_id = $this->request->param('id');
        $news_del = ORM::factory('cheers_main_new', $news_id);
        if ($news_del->loaded()) {
            
            
            $news_del->delete();

            Message::set('删除成功！');
            Request::current()->redirect('/admin/news/list');
        } else {
            Message::set('操作失败,请您重试！', 'red');
            Request::current()->redirect('/admin/news/list');
        }
    }

    /*
     * 删除多个新闻
     */

    public function action_delete_all() {

        $all_newsid = isset($_GET['deleteall']) ? $_GET['deleteall'] : '';

        if (!empty($all_newsid)) {
            $newsid_string = "'";
            foreach ($all_newsid as $key => $value) {
                $newsid_string .= $value . "','";
            }

            $newsid_string = rtrim(rtrim($newsid_string, "'"), ',');

            $query = DB::query(Database::UPDATE, 'UPDATE news set del_id=1 where newsid in(' . $newsid_string . ')')
                    ->execute();

            if (isset($query)) {
                Message::set('新闻删除成功！');
                Request::current()->redirect('/admin/news/list/');
            } else {
                Message::set('新闻删除失败！', 'red');
                Request::current()->redirect('/admin/news/list/');
            }
        } else {
            Message::set('请选择要删除的新闻！', 'yellow');
            Request::current()->redirect('/admin/news/list/');
        }
    }

    /**
     * 新闻修改
     */
    public function action_edit() {
        $name_template = '<a href="/admin/news/list/{id}" title="{name}新闻列表">{name}</a>';
        $conditional_name_template = '<a href="/admin/news/list/{id}" title="{name}新闻列表">[ {name} ]</a>';
        $content_data['catalog_tree'] = Catehelp::get_left_tree($name_template, $conditional_name_template, array('table' => 'cheers_main_newstypes', 'id' => 'chr_typeid', 'name' => 'chr_typename'));
        $content_data['product_ids'] = array();
        $content_data['is_conditional'] = FALSE;
        $catalog_opt_template = array(
            'name_box' => '<option value="{id}" {selected}>{indentation}{name}</option>',
            'indentation' => '&nbsp;|&nbsp;&nbsp;'
        );
        $news_id = $this->request->param('id');
        $news_detail = DB::select()->from('cheers_main_news')
                ->join('cheers_main_newscontexts', 'LEFT')
                ->on('cheers_main_newscontexts.chr_newsid', '=', 'cheers_main_news.chr_newsid')
                ->where('cheers_main_news.chr_newsid', '=', $news_id)
                ->execute()
                ->as_array();

        if (!isset($news_detail[0]['chr_newsid'])) {
            $news_detail[0]['chr_newsid'] = $news_id;
        }
        $content_data['catalog_opt'] = Catehelp::tree_to_str(Catehelp::get_tree($catalog_opt_template, 0, 0, array('table' => 'cheers_main_newstypes', 'id' => 'chr_typeid', 'name' => 'chr_typename'), $news_detail[0]['chr_typeid']));
        if ($_POST) {
            $current_time = time();
            $news_detail_save = ORM::factory('cheers_main_new', $news_id);
            $data['chr_title'] = htmlspecialchars(Arr::get($_POST, 'chr_title', ''));
            $data['chr_typeid'] = Arr::get($_POST, 'chr_typeid', '');
            $data['chr_source'] = strtolower(Arr::get($_POST, 'chr_source', ''));
            $data['chr_author'] = htmlspecialchars(Arr::get($_POST, 'chr_author', ''));
            $data['chr_definedate'] = Arr::get($_POST, 'chr_createdate', '');
            $data['chr_tag'] = Arr::get($_POST, 'chr_tag', '');
            $data['chr_ticks'] = Arr::get($_POST, 'chr_ticks', '');
            $data['chr_introduction'] = htmlspecialchars(Arr::get($_POST, 'chr_introduction', ''));
            $data['chr_keywords'] = htmlspecialchars(Arr::get($_POST, 'chr_keywords', ''));
            $data['chr_desc'] = htmlspecialchars(Arr::get($_POST, 'chr_desc', ''));
            $data['chr_editdate'] = $current_time;
            $user = User::instance()->logged_in();
            $data['chr_editor'] = $user['chr_uid'];
            $news_detail_save->values($data);
            if ($news_detail_save->check()) {
                $news_detail_save->save();
                unset($data);
                $data['chr_context'] = htmlspecialchars(Arr::get($_POST, 'chr_context', ''));
                if ($data['chr_context']) {
                    $news_context = ORM::factory('cheers_main_newscontext');
                    $news_context->chr_newsid = $news_detail_save->chr_newsid;
                    $news_context->chr_context = $data['chr_context'];
                    if ($news_context->check()) {
                        $news_context->save();
                    }
                }
                if ($news_detail_save->saved()) {
                    Message::set('新闻编辑成功');
                    Request::current()->redirect('admin/news/edit/' . $news_id);
                } else {
                    Message::set('新闻编辑失败', 'error');
                    Request::current()->redirect('admin/news/edit/' . $news_id);
                }
            }
        }


        $content = View::factory('admin/news/news_edit', $content_data)
                ->set('data', $news_detail[0])
                ->render();

        $this->template = View::factory('admin/template')->set('content', $content);
    }

    /*
     * 新闻修改的执行操作
     */

    public function action_edit_go() {
        if ($_POST) {
            $news_id = $this->request->param('id');
            $news = ORM::factory('new', $news_id);

            if ($news->loaded()) {

                $news->newsname = $_POST['newsname'];
                $news->newscontents = $_POST['newscontents'];
                $news->newsclick = $_POST['newsclick'];
                $news->category = $_POST['category'];
                $news->author = $_POST['author'];
                $news->updatetime = time();

                if ($news->check()) {
                    $news->save();
                    if ($news->saved()) {
                        Message::set('新闻修改成功');
                        Request::current()->redirect('/admin/news/edit/' . $news_id . '/');
                    }
                } else {
                    Message::set('新闻修改出错', 'red');
                    Request::current()->redirect('/admin/news/edit/' . $news_id . '/');
                }
            }
        }
    }

}

?>
